<?PHP

/*
  Registration/Login script from HTML Form Guide
  V1.0

  This program is free software published under the
  terms of the GNU Lesser General Public License.
  http://www.gnu.org/copyleft/lesser.html


  This program is distributed in the hope that it will
  be useful - WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A
  PARTICULAR PURPOSE.

  For updates, please visit:
  http://www.html-form-guide.com/php-form/php-registration-form.html
  http://www.html-form-guide.com/php-form/php-login-form.html

 */
date_default_timezone_set('America/Los_Angeles');
include_once dirname(dirname(__FILE__)) . '/core/class.phpmailer.php';
require_once dirname(dirname(__FILE__)) . "/db/db.php";
//require_once("class.phpmailer.php");
//include_once('Mail.php');
//include_once('Mail/mime.php');
require_once("formvalidator.php");

//require_once (dirname(dirname(__FILE__)) . '/common.php');

class UserManager {

    var $admin_email;
    var $from_address;
    var $username;
    var $pwd;
    var $database;
    var $tablename;
    var $rand_key = 'JBMdaTkGbe3qyE2';
    var $error_message;

    //-----Initialization -------
    function UserManager() {
        $this->tablename = 'users';
    }

    function SetAdminEmail($email) {
        $this->admin_email = $email;
    }

    function SetWebsiteName($sitename) {
        $this->sitename = $sitename;
    }

    function SetRandomKey($key) {
        $this->rand_key = $key;
    }

    //-------Main Operations ----------------------
    function RegisterUser($is_web = 0) {

        $formvars = array();

        if (!$this->ValidateRegistrationSubmission()) {
            return false;
        }

        $this->CollectRegistrationSubmission($formvars);

        if (!$this->SaveToDatabase($formvars, $is_web)) {
            return false;
        }

        /* if (!$this->SendUserConfirmationEmail($formvars)) {
          return false;
          } */

        return true;
    }

    function Login() {
        if (empty($_POST['email'])) {
            $this->HandleError("UserName is empty!");
            return false;
        }

        if (empty($_POST['password'])) {
            $this->HandleError("Password is empty!");
            return false;
        }

        $username = trim($_POST['email']);
        $password = trim($_POST['password']);

        if (!isset($_SESSION)) {
            session_start();
        }
        if (!$this->CheckLoginInDB($username, $password)) {
            return false;
        }

        $_SESSION[$this->GetLoginSessionVar()] = $username;

        $time = time();
        $cookie_time = (3600 * 24 * 30); // 30 days
        if ($_POST ["remember_user"]) {
            // Check to see if the 'setcookie' box was ticked to remember the user
            setcookie("username", $username, $time + $cookie_time, '/'); // Sets the cookie username
            setcookie("password", md5($password), $time + $cookie_time, '/'); // Sets the cookie password
            setcookie("remember_user", "yes", $time + $cookie_time * 12, '/'); // Sets the cookie remember user
        } else {
            $this->removeAllCookiesFromDomain();
            setcookie("remember_user", "", $time - 3600, '/'); // Sets the cookie remember user
        }
        return true;
    }

    function CheckLogin() {
        if (!isset($_SESSION)) {
            session_start();
        }
      
        $sessionvar = $this->GetLoginSessionVar();
        if (empty($_SESSION[$sessionvar])) {
            if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
                $username = $_COOKIE['username'];
                $pwdmd5 = $_COOKIE['password'];
                $qry = "Select * from $this->tablename where active=1 and email='$username' and password='$pwdmd5'";
                $result = mysql_query($qry);
                if (!$result || mysql_num_rows($result) <= 0) {
                    return false;
                } else {
                    $_SESSION[$this->GetLoginSessionVar()] = $username;
                    return true;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    function UserFullName() {
        return isset($_SESSION['name_of_user']) ? $_SESSION['name_of_user'] : '';
    }

    function UserEmail() {
        return isset($_SESSION['email_of_user']) ? $_SESSION['email_of_user'] : '';
    }

    function removeAllCookiesFromDomain() {
        setcookie("username", '', time() - 3600, '/');
        setcookie("password", '', time() - 3600, '/');
    }

    function LogOut() {
        session_start();
        $sessionvar = $this->GetLoginSessionVar();
        $_SESSION[$sessionvar] = NULL;
        unset($_SESSION[$sessionvar]);
        $this->removeAllCookiesFromDomain();
        return true;
    }

    function EmailResetPasswordLink() {
        if (empty($_POST['email'])) {
            $this->HandleError("Email is empty!");
            return false;
        }
        $user_rec = array();
        if (false === $this->GetUserFromEmail($_POST['email'], $user_rec)) {
            return false;
        }
        if (false === $this->SendNewPassword($user_rec)) {
            return false;
        }
        return true;
    }

    function ResetPassword() {
        if (empty($_GET['email'])) {
            $this->HandleError("Email is empty!");
            return false;
        }
        if (empty($_GET['code'])) {
            $this->HandleError("reset code is empty!");
            return false;
        }
        $email = trim($_GET['email']);
        $code = trim($_GET['code']);

        if ($this->GetResetPasswordCode($email) != $code) {
            $this->HandleError("Bad reset code!");
            return false;
        }

        $user_rec = array();
        if (!$this->GetUserFromEmail($email, $user_rec)) {
            return false;
        }

        $new_password = $this->ResetUserPasswordInDB($user_rec);
        if (false === $new_password || empty($new_password)) {
            $this->HandleError("Error updating new password");
            return false;
        }


        return true;
    }

    function ChangePassword() {
        if (!$this->CheckLogin()) {
            $this->HandleError("Not logged in!");
            return false;
        }

        if (empty($_POST['oldpwd'])) {
            $this->HandleError("Old password is empty!");
            return false;
        }
        if (empty($_POST['newpwd'])) {
            $this->HandleError("New password is empty!");
            return false;
        }

        $user_rec = array();
        if (!$this->GetUserFromEmail($this->UserEmail(), $user_rec)) {
            return false;
        }

        $pwd = trim($_POST['oldpwd']);

        if ($user_rec['password'] != md5($pwd)) {
            $this->HandleError("The old password does not match!");
            return false;
        }
        $newpwd = trim($_POST['newpwd']);

        if (!$this->ChangePasswordInDB($user_rec, $newpwd)) {
            return false;
        }
        return true;
    }

    //-------Public Helper functions -------------
    function GetSelfScript() {
        return htmlentities($_SERVER['PHP_SELF']);
    }

    function SafeDisplay($value_name) {
        if (empty($_POST[$value_name])) {
            return'';
        }
        return htmlentities($_POST[$value_name]);
    }

    function RedirectToURL($url) {
        header("Location: $url");
        exit;
    }

    function GetSpamTrapInputName() {
        return 'sp' . md5('KHGdnbvsgst' . $this->rand_key);
    }

    function GetErrorMessage() {
        if (empty($this->error_message)) {
            return '';
        }
        $errormsg = nl2br(htmlentities($this->error_message));
        return $errormsg;
    }

    //-------Private Helper functions-----------

    function HandleError($err) {
        $this->error_message .= $err . "<br>";
    }

    function HandleDBError($err) {
        $this->HandleError($err . "<br> mysqlerror:" . mysql_error());
    }

    function GetFromAddress() {
        if (!empty($this->from_address)) {
            return $this->from_address;
        }

        $host = $_SERVER['SERVER_NAME'];

        $from = "notification@igniteapplication.com";
        return $from;
    }

    function GetLoginSessionVar() {
        $retvar = md5($this->rand_key);
        $retvar = 'usr_' . substr($retvar, 0, 10);
        return $retvar;
    }

    function CheckLoginInDB($username, $password) {

        $username = $this->SanitizeForSQL($username);
        $pwdmd5 = md5($password);

        $qry = "Select * from $this->tablename where email='$username' and password='$pwdmd5'";

        $result = mysql_query($qry);

        if (!$result || mysql_num_rows($result) <= 0) {

            $this->HandleError("The username and password do not match");
            return false;
        }
        $row = mysql_fetch_assoc($result);
        if ($row["active"] == 0) {
            $this->HandleError("Your account has not been activated. Please check your email to activate your account.");
            return false;
        }
        $_SESSION['Login']['UserID'] = $row['id'];

        return true;
    }

    protected $_current_user_info = null;

    function getCurrentUser() {
        if (!$this->CheckLogin()) {
            return false;
        }

        if ($this->_current_user_info === null) {
            if (!isset($_SESSION['Login']['UserID'])) {
                $this->_current_user_info = false;
                return false;
            }

            $user_id = intval($_SESSION['Login']['UserID']);

            if ($user_id < 1) {
                $this->_current_user_info = false;
                return false;
            }

            $result = mysql_query("Select * from $this->tablename where id='$user_id' limit 1");

            if (!$result || mysql_num_rows($result) <= 0) {
                $this->_current_user_info = false;
                return false;
            }

            $this->_current_user_info = mysql_fetch_object($result);
        }

        return $this->_current_user_info;
    }

    public function getCurrentUserFullname() {
        $user = $this->getCurrentUser();

        if (!$user) {
            return '';
        }

        return $user->first_name . ' ' . $user->last_name;
    }

    public function getCurrentUserAvatar() {
        $user = $this->getCurrentUser();

        if (!$user) {
            return '';
        }

        $folder = $this->GetAbsoluteURLFolder();

        if (preg_match('/mobile\/*$/i', $folder)) {
            $folder = dirname($folder);
        }

        return $folder . ($user->photo ? '/photos/' . $user->photo : '/include/images/noAva.png');
    }

    function ResetUserPasswordInDB($user_rec) {
        $new_password = substr(md5(uniqid()), 0, 10);

        if (false == $this->ChangePasswordInDB($user_rec, $new_password)) {
            return false;
        }
        return $new_password;
    }

    function ChangePasswordInDB($user_rec, $newpwd) {

        $qry = "Update $this->tablename Set password='" . md5($newpwd) . "' Where  id=" . $user_rec['id'] . "";

        if (!mysql_query($qry)) {
            $this->HandleDBError("Error updating the password \nquery:$qry");
            return false;
        }
        return true;
    }

    function GetUserFromEmail($email, &$user_rec) {

        $email = $this->SanitizeForSQL($email);

        $result = mysql_query("Select * from $this->tablename where email='$email'");

        if (!$result || mysql_num_rows($result) <= 0) {
            $this->HandleError("User does not exit");
            return false;
        }
        $user_rec = mysql_fetch_assoc($result);


        return true;
    }

   
    function GetResetPasswordCode($email) {
        return substr(md5($email . $this->sitename . $this->rand_key), 0, 10);
    }

    function SendNewPassword($user_rec) {
        $new_password = $this->ResetUserPasswordInDB($user_rec);
        $host = "email-smtp.us-east-1.amazonaws.com";
        $username = "AKIAJNJOJCPFI5LV5GDQ";
        $password = "AmtkjqZl87GOr1+Y7ELKOpMHZSkLaHxz6aZ6FzDA/ZWK";
        
        $recipients = array();
        $recipients[] = $user_rec['email'];

        $headers = array('From' => 'Nike Recruitment Application<notification@igniteapplication.com>',
            'To' => $user_rec['email'],
            'Subject' => "Your request to reset your password");

        $smtp = Mail::factory('smtp', array('host' => $host,
                    'auth' => true,
                    'username' => $username,
                    'password' => $password));

        $message = new Mail_mime();
        $message->setHTMLBody('<img src="'.$this->GetAbsoluteURLFolder().'include/images/ignite_email_logo.png"/><br>' . "You have requested that your password be resent. Your password is: " . $new_password . " <br>If you did not make this request, please contact us at support@igniteapplication.com. We recommend that you change your password immediately upon logging into your application.<br> Thank you.<br> The Nike Recruitment Application Team");
        $body = $message->get();
        $headers = $message->headers($headers);

        $result = $smtp->send($recipients, $headers, $body);

        if ($result != 1) {
            $this->HandleError("Failed sending user welcome email.");
            return false;
        }
        return true;
    }

    function SendResetPasswordLink($user_rec) {
        $host = "email-smtp.us-east-1.amazonaws.com";
        $username = "AKIAJNJOJCPFI5LV5GDQ";
        $password = "AmtkjqZl87GOr1+Y7ELKOpMHZSkLaHxz6aZ6FzDA/ZWK";
        $recipients = array();
        $recipients[] = $user_rec['email'];

        $headers = array('From' => 'Nike Recruitment Application<notification@igniteapplication.com>',
            'To' => $user_rec['email'],
            'Subject' => "Your request to reset your password");

        $smtp = Mail::factory('smtp', array('host' => $host,
                    'auth' => true,
                    'username' => $username,
                    'password' => $password));

        $message = new Mail_mime();
        $message->setHTMLBody('<img src="'.$this->GetAbsoluteURLFolder().'include/images/ignite_email_logo.png"/><br>' . "Hello,<br>" .
                "There was a request to reset your password at " . $this->sitename . "<br>" .
                "Please click the link below to complete the request: <br>" . $link . "<br>" .
                "Regards,<br>" .
                "Webmaster<br>" .
                $this->sitename);
        $body = $message->get();
        $headers = $message->headers($headers);

        $result = $smtp->send($recipients, $headers, $body);

        if ($result != 1) {
            $this->HandleError("Failed sending user welcome email.");
            return false;
        }
        return true;
    }

    function ValidateRegistrationSubmission() {
        //This is a hidden input field. Humans won't fill this field.
        if (!empty($_POST[$this->GetSpamTrapInputName()])) {
            //The proper error is not given intentionally
            $this->HandleError("Automated submission prevention: case 2 failed");
            return false;
        }

        $validator = new FormValidator();
        $validator->addValidation("email", "email", "The input for Email should be a valid email value");
        $validator->addValidation("email", "req", "Please fill in Email");
        $validator->addValidation("password", "req", "Please fill in Password");


        if (!$validator->ValidateForm()) {
            $error = '';
            $error_hash = $validator->GetErrors();
            foreach ($error_hash as $inpname => $inp_err) {
                $error .= $inpname . ':' . $inp_err . "\n";
            }
            $this->HandleError($error);
            return false;
        }
        return true;
    }

    function CollectRegistrationSubmission(&$formvars) {
        $formvars['email'] = $this->Sanitize($_POST['email']);
        $formvars['password'] = $_POST['password'];
        $formvars['confirmation_code'] = md5($formvars['password'] . $formvars['email']);
        $formvars['phone'] = $this->SanitizeForSQL($_POST['phone']);
        if (isset($_POST["school_id"]) && $_POST["school_id"] > 0) {
            $formvars['school_id'] = $_POST["school_id"];
        } else {
            $formvars['school_id'] = 0;
        }
        $formvars['is_graduate'] = isset($_POST["is_graduate"]) ? intval($_POST["is_graduate"]) : 0;
        $formvars['graduation_year'] = isset($_POST["graduate_year"]) ? intval($_POST["graduate_year"]) : 0;
        $formvars['graduation_month'] = isset($_POST["graduate_month"]) ? intval($_POST["graduate_month"]) : 0;
        $formvars['firstname'] = $this->SanitizeForSQL($_POST['firstname']);
        $formvars['lastname'] = $this->SanitizeForSQL($_POST['lastname']);
        $formvars['active'] = 0;
        $admin_code = isset($_POST["admin_code"]) ? $_POST["admin_code"] : "";
        if ($admin_code !== "") {
            $formvars['user_role'] = 1;
        } else {
            $formvars['user_role'] = 2;
        }
    }

    function SendUserEmail(&$formvars) {

        $subject = "Your registration with Nike Recruitment Application";
        $content = "Hello<br>" .
                "Thank you for submitting your registration information to Ignite." .
                "<br>" .
                "Regards,<br>" .
                "Webmaster<br>" .
                $this->sitename;
        $sender_email = "notification@igniteapplication.com";
        $mailer = new PHPMailer();
        $mailer->IsHTML(true);
        $mailer->CharSet = 'utf-8';
        $mailer->AddAddress($formvars['email']);
        $mailer->Subject = $subject;
        $mailer->From = $sender_email;
        $mailer->Body = '<img src="'.$this->GetAbsoluteURLFolder().'include/images/ignite_email_logo.png"/><br>' . $content;

        if (!$mailer->Send()) {
            $this->HandleError("Failed sending user welcome email.");
        } else {
            return true;
        }
    }

    function GetAbsoluteURLFolder() {
        $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
        $scriptFolder .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
        return $scriptFolder;
    }

    function SaveToDatabase(&$formvars, $is_web = 0) {

        if (!$this->Ensuretable()) {
            return false;
        }
        if (!$this->IsFieldUnique($formvars['email'], 'email')) {
            $this->HandleError("This email is already registered");
            return false;
        }

        if (!$this->InsertIntoDB($formvars, $is_web)) {
            $this->HandleError("Inserting to Database failed!");
            return false;
        }
        return true;
    }

    function IsFieldUnique($field, $fieldname) {
        $field_val = $this->SanitizeForSQL($field);
        $qry = "select email from $this->tablename where $fieldname='" . $field_val . "'";
        $result = mysql_query($qry);
        if ($result && mysql_num_rows($result) > 0) {
            return false;
        }
        return true;
    }

    function Ensuretable() {
        $result = mysql_query("SHOW COLUMNS FROM $this->tablename");
        if (!$result || mysql_num_rows($result) <= 0) {
            return $this->CreateTable();
        }
        return true;
    }

    function SendUserConfirmationEmail(&$formvars) {
        $confirmcode = $formvars['confirmcode'];
        $confirm_url = $this->GetAbsoluteURLFolder() . 'confirm.php?code=' . $confirmcode;
        
        $host = "email-smtp.us-east-1.amazonaws.com";
        $username = "AKIAJNJOJCPFI5LV5GDQ";
        $password = "AmtkjqZl87GOr1+Y7ELKOpMHZSkLaHxz6aZ6FzDA/ZWK";
        
        $recipients = array();
        $recipients[] = $formvars['email'];

        $headers = array('From' => 'Nike Recruitment Application<notification@igniteapplication.com>',
            'To' => $formvars['email'],
            'Subject' => "Your registration with Nike Recruitment Application");

        $smtp = Mail::factory('smtp', array('host' => $host,
                    'auth' => true,
                    'username' => $username,
                    'password' => $password));

        $message = new Mail_mime();
        $message->setHTMLBody('<img src="'.$this->GetAbsoluteURLFolder().'include/images/ignite_email_logo.png"/><br>' . "Thank you for submitting your registration information to Nike Recruitment Application!                     
                     <br>
                     Please click <a href='" . $confirm_url . "'>here</a> to activate your account.                     
                    <br>The Nike Recruitment Application Team");
        $body = $message->get();
        $headers = $message->headers($headers);

        $result = $smtp->send($recipients, $headers, $body);

        if ($result != 1) {
            $this->HandleError("Failed sending email.");
            return false;
        }
        return true;
    }

    function UpdateDBRecForConfirmation(&$user_rec) {

        $confirmcode = $this->SanitizeForSQL($_GET['code']);
        $query = "Select email from $this->tablename where confirmation_code='$confirmcode'";
        $result = mysql_query($query);
        if (!$result || mysql_num_rows($result) <= 0) {
            $this->HandleError("Wrong confirmation code.");
            return false;
        }
        $row = mysql_fetch_assoc($result);

        $qry = "Update $this->tablename Set confirmation_code='' Where  confirmation_code='$confirmcode'";

        if (!mysql_query($qry)) {
            $this->HandleDBError("Error inserting data to the table\nquery:$qry");
            return false;
        }
        return true;
    }

    function ConfirmUser() {
        if (empty($_GET['code']) || strlen($_GET['code']) <= 10) {
            $this->HandleError("Please provide the confirmation code");
            return false;
        }
        $user_rec = array();
        if (!$this->UpdateDBRecForConfirmation($user_rec)) {
            return false;
        }


        return true;
    }

    function InsertIntoDB(&$formvars, $is_web = 0) {
        $confirmcode = $this->MakeConfirmationMd5($formvars['email']);
        $insert_query = "INSERT INTO " . $this->tablename . " (`email`,`phone`,`school_id`,
                `is_graduate`,`first_name`,`last_name`,`timestamp`,`active`,`login_count`,`password`,`confirmation_code`,
                `reset_password_code`,`reset_password_code_expiration`,`user_role`,`graduation_year`,`graduation_month`) VALUES 
                ('" . $this->SanitizeForSQL($formvars['email']) . "','" . $formvars['phone'] . "',
                " . $formvars['school_id'] . "," . $formvars['is_graduate'] . ",
                '" . $formvars['firstname'] . "','" . $formvars['lastname'] . "',now(),
                " . $formvars['active'] . ",0,'" . md5($formvars['password']) . "',
               '" . $formvars['confirmation_code'] . "',NULL,NULL," . $formvars['user_role'] . ",
                ".$formvars['graduation_year'].",".$formvars['graduation_month'].")";
       
        $result = mysql_query($insert_query);
        if (!$result) {
            $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
            return false;
        } 
        if (!isset($_SESSION)) {
            session_start();
        }

        return true;
    }

    function MakeConfirmationMd5($email) {
        $randno1 = rand();
        $randno2 = rand();
        return md5($email . $this->rand_key . $randno1 . '' . $randno2);
    }

    function SanitizeForSQL($str) {
        if (function_exists("mysql_real_escape_string")) {
            $ret_str = mysql_real_escape_string($str);
        } else {
            $ret_str = addslashes($str);
        }
        return $ret_str;
    }

    function Sanitize($str, $remove_nl = true) {
        $str = $this->StripSlashes($str);

        if ($remove_nl) {
            $injections = array('/(\n+)/i',
                '/(\r+)/i',
                '/(\t+)/i',
                '/(%0A+)/i',
                '/(%0D+)/i',
                '/(%08+)/i',
                '/(%09+)/i'
            );
            $str = preg_replace($injections, '', $str);
        }

        return $str;
    }

    function StripSlashes($str) {
        if (get_magic_quotes_gpc()) {
            $str = stripslashes($str);
        }
        return $str;
    }

    function getUserInfoByEmail($email) {
        $qry = "Select * from $this->tablename where active=1 and email='$email'";
        $result = mysql_query($qry);

        if (!$result || mysql_num_rows($result) <= 0) {
            $this->HandleError("Not found user");
            return false;
        }

        $row = mysql_fetch_assoc($result);
        return $row;
    }

    function updateStatusNotification($notification, $user_id) {
        $qry = "Update $this->tablename Set notification='$notification' Where  id=$user_id";

        if (!mysql_query($qry)) {
            $this->HandleDBError("Error updating the password \nquery:$qry");
            return false;
        }
        return true;
    }

}

?>